﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MPMovieCatalog.Domain;
using MPMovieCatalog.Util;

namespace MPMovieCatalog.Forms
{
    public partial class EditForm : Form
    {
        private long movieId;
        private string movieTitle;

        public EditForm()
        {
            InitializeComponent();
            UpdateUI();
        }

        public MovieInfo Data
        {
            get
            {
                MovieInfo movieInfo = new MovieInfo();
                movieInfo.Id = movieId;

                movieInfo.Name = titleTextBox.Text;
                movieInfo.Tagline = taglineTextBox.Text;
                movieInfo.Director = directorTextBox.Text;
                movieInfo.Writer = writerTextBox.Text;
                movieInfo.Runtime = (int)runtimeUpDown.Value;
                movieInfo.IMDBNumber = imdbNumberTextBox.Text;
                movieInfo.IMDBVotes = imdbVotesTextBox.Text;
                movieInfo.MPAARating = mpaaRatingComboBox.Text;
                movieInfo.IsWatched = watchedCheckBox.Checked;
                movieInfo.DiscId = (discIdUpDown.Value > 0) ? discIdUpDown.Value.ToString() : "";

                if (yearUpDown.Value > 0)
                {
                    movieInfo.Year = yearUpDown.Value.ToString();
                }
                
                if (!string.IsNullOrEmpty(imdbRatingTextBox.Text))
                {
                    movieInfo.IMDBRating = imdbRatingTextBox.Text.Replace('.', ',');

                    double result;
                    if (!double.TryParse(movieInfo.IMDBRating, out result))
                    {
                        movieInfo.IMDBRating = "0";
                    }
                }
                else
                {
                    movieInfo.IMDBRating = "0";
                }

                movieInfo.Description = descriptionTextBox.Text;

                movieInfo.PictureFileName = pictureFileTextBox.Text;

                foreach (Genre genre in genresCheckedListBox.CheckedItems)
                {
                    movieInfo.AddGenre(genre);
                }

                foreach (Actor actor in movieActorsListBox.Items)
                {
                    movieInfo.AddActor(actor);
                }

                foreach (ShareFile file in filesListBox.Items)
                {
                    movieInfo.AddFile(file);
                }

                return movieInfo;
            }
            set
            {
                if (value != null)
                {
                    movieId = value.Id;
                    movieTitle = value.Name;

                    titleTextBox.Text = value.Name;
                    taglineTextBox.Text = value.Tagline;
                    directorTextBox.Text = value.Director;
                    writerTextBox.Text = value.Writer;
                    imdbRatingTextBox.Text = value.IMDBRating;
                    imdbNumberTextBox.Text = value.IMDBNumber;
                    imdbVotesTextBox.Text = value.IMDBVotes;
                    runtimeUpDown.Value = decimal.Parse(value.Runtime.ToString());
                    mpaaRatingComboBox.Text = value.MPAARating;
                    watchedCheckBox.Checked = value.IsWatched;
                    discIdUpDown.Value = (string.IsNullOrEmpty(value.DiscId)) ? 0 : decimal.Parse(value.DiscId.ToString());

                    descriptionTextBox.Text = value.Description;

                    pictureFileTextBox.Text = value.PictureFileName;
                    pictureBox.ImageLocation = value.PictureFileName;

                    if (!string.IsNullOrEmpty(value.Year))
                    {
                        yearUpDown.Value = decimal.Parse(value.Year);
                    }
                    else
                    {
                        yearUpDown.Value = 1900;
                    }


                    value.Genres.Sort();
                    foreach (Genre genre in value.Genres)
                    {
                        genresCheckedListBox.Items.Add(genre, true);
                    }

                    AvailableGenres.Sort();
                    foreach (Genre availGenre in AvailableGenres)
                    {
                        genresCheckedListBox.Items.Add(availGenre);
                    }

                    foreach (Actor actor in value.Actors)
                    {
                        movieActorsListBox.Items.Add(actor);
                    }

                    foreach (Actor availActor in AvailableActors)
                    {
                        availableActorsListBox.Items.Add(availActor);
                    }

                    foreach (ShareFile file in value.Files)
                    {
                        filesListBox.Items.Add(file);
                    }
                }

                this.Text = movieId > 0 ? string.Format(ResourceUtils.GetString("edit", 25), movieTitle) : ResourceUtils.GetString("edit", 24);
            }
        }

        public ArrayList AvailableGenres { get; set; }

        public ArrayList AvailableActors { get; set; }

        private void browsePictureFileButton_Click(object sender, EventArgs e)
        {
            openFileDialog.FileName = pictureFileTextBox.Text;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                pictureBox.ImageLocation = openFileDialog.FileName;
                pictureFileTextBox.Text = openFileDialog.FileName;
            }
        }

        private void addGenreButton_Click(object sender, EventArgs e)
        {
            if (newGenreTextBox.Text != null && !"".Equals(newGenreTextBox.Text))
            {
                string name = newGenreTextBox.Text;
                int index = genresCheckedListBox.FindStringExact(name);
                if (index < 0)
                {
                    genresCheckedListBox.BeginUpdate();

                    List<Genre> checkedGenres = new List<Genre>();
                    List<Genre> uncheckedGenres = new List<Genre>();
                    for (int i = 0; i < genresCheckedListBox.Items.Count; i++)
                    {
                        Genre genre = (Genre)genresCheckedListBox.Items[i];
                        if (genresCheckedListBox.GetItemChecked(i))
                        {
                            checkedGenres.Add(genre);
                        }
                        else
                        {
                            uncheckedGenres.Add(genre);
                        }
                    }

                    checkedGenres.Sort(NamedEntity.CompareByName);

                    Genre newGenre = new Genre();
                    newGenre.Name = name;

                    uncheckedGenres.Add(newGenre);
                    uncheckedGenres.Sort(NamedEntity.CompareByName);

                    genresCheckedListBox.Items.Clear();

                    foreach (Genre checkedGenre in checkedGenres)
                    {
                        genresCheckedListBox.Items.Add(checkedGenre, true);
                    }

                    foreach (Genre uncheckedGenre in uncheckedGenres)
                    {
                        genresCheckedListBox.Items.Add(uncheckedGenre);
                    }


                    index = genresCheckedListBox.FindStringExact(name);
                    genresCheckedListBox.EndUpdate();
                }

                genresCheckedListBox.SelectedIndex = index;
                newGenreTextBox.Clear();
            }
        }

        private void mapActorButton_Click(object sender, EventArgs e)
        {
            if (availableActorsListBox.SelectedItems == null) return;
            foreach (Actor actor in availableActorsListBox.SelectedItems)
            {
                movieActorsListBox.Items.Add(actor);
            }

            for (int i = availableActorsListBox.SelectedItems.Count - 1; i >= 0; i--)
            {
                availableActorsListBox.Items.Remove(availableActorsListBox.SelectedItems[i]);
            }
        }

        private void unmapActorButton_Click(object sender, EventArgs e)
        {
            if (movieActorsListBox.SelectedItems == null) return;
            foreach (Actor actor in movieActorsListBox.SelectedItems)
            {
                availableActorsListBox.Items.Add(actor);
            }

            for (int i = movieActorsListBox.SelectedItems.Count - 1; i >= 0; i--)
            {
                movieActorsListBox.Items.Remove(movieActorsListBox.SelectedItems[i]);
            }
        }

        private void addActorButton_Click(object sender, EventArgs e)
        {
            if (newActorTextBox.Text != null && !"".Equals(newActorTextBox.Text))
            {
                string name = newActorTextBox.Text;
                int index = availableActorsListBox.FindStringExact(name);
                if (index < 0)
                {
                    Actor actor = new Actor();
                    actor.Name = name;

                    index = availableActorsListBox.Items.Add(actor);
                }
                availableActorsListBox.SelectedIndex = index;

                newActorTextBox.Clear();
            }
        }

        private void addFileButton_Click(object sender, EventArgs e)
        {
            using (FileChooseForm fileChooseForm = new FileChooseForm())
            {
                if (fileChooseForm.ShowDialog(this) == DialogResult.OK)
                {
                    foreach (ShareFile file in fileChooseForm.Files)
                    {
                        filesListBox.Items.Add(file);
                    }
                }
            }
        }

        private void deleteFileButton_Click(object sender, EventArgs e)
        {
            if (filesListBox.SelectedItem != null)
            {
                filesListBox.Items.Remove(filesListBox.SelectedItem);
            }
        }

        private void searchButton_Click(object sender, EventArgs e)
        {
            using (SearchMovieForm searchMovieForm = new SearchMovieForm())
            {
                searchMovieForm.SearchString = titleTextBox.Text;
                if (searchMovieForm.ShowDialog(this) == DialogResult.OK)
                {
                	MovieInfo movieInfo = searchMovieForm.MovieInfo;
                	movieInfo.Id = movieId;
                	             
           			UpdateList(movieActorsListBox, movieInfo.Actors, AvailableActors);
                	availableActorsListBox.Items.Clear();

           			AvailableGenres.Clear();
           			UpdateList(genresCheckedListBox, movieInfo.Genres, AvailableGenres);
           			
                    Data = movieInfo;
                }
            }
        }
        
        private void UpdateList(ListBox listBox, ArrayList list, ArrayList availableList)
        {
        	foreach (NamedEntity entity in listBox.Items)
   			{
        		if (entity.Id > 0)
           		{
        			availableList.Add(entity);
           		}
        	}
        	listBox.Items.Clear();

            availableList.Sort();
        	foreach (NamedEntity entity in list)
        	{
        		int index = availableList.BinarySearch(entity);
        		if (index > -1)
        		{
        			entity.Id = (availableList[index] as NamedEntity).Id;
        			availableList.RemoveAt(index);
        		}
        	}
        }
        
        private void UpdateUI()
        {
            movieTabPage.Text = ResourceUtils.GetString("edit", 0);
            titleLabel.Text = ResourceUtils.GetString("edit", 1);
            searchButton.Text = ResourceUtils.GetString("edit", 2);
            taglineLabel.Text = ResourceUtils.GetString("edit", 3);
            directorLabel.Text = ResourceUtils.GetString("edit", 4);
            writerLabel.Text = ResourceUtils.GetString("edit", 5);
            yearLabel.Text = ResourceUtils.GetString("edit", 6);
            runtimeLabel.Text = ResourceUtils.GetString("edit", 7);
            imdbGroupBox.Text = ResourceUtils.GetString("edit", 8);
            imdbRatingLabel.Text = ResourceUtils.GetString("edit", 9);
            imdbNumberLabel.Text = ResourceUtils.GetString("edit", 10);
            imdbVotesLabel.Text = ResourceUtils.GetString("edit", 11);
            mpaaRatingLabel.Text = ResourceUtils.GetString("edit", 12);
            genresGroupBox.Text = ResourceUtils.GetString("edit", 13);
            actorsGroupBox.Text = ResourceUtils.GetString("edit", 14);
            descriptionTabPage.Text = ResourceUtils.GetString("edit", 15);
            pictureTabPage.Text = ResourceUtils.GetString("edit", 16);
            pathLabel.Text = ResourceUtils.GetString("edit", 17);
            browsePictureFileButton.Text = ResourceUtils.GetString("edit", 18);
            filesTabPage.Text = ResourceUtils.GetString("edit", 19);
            addFileButton.Text = ResourceUtils.GetString("edit", 20);
            deleteFileButton.Text = ResourceUtils.GetString("edit", 21);
            saveButton.Text = ResourceUtils.GetString("edit", 22);
            cancelButton.Text = ResourceUtils.GetString("edit", 23);
            watchedCheckBox.Text = ResourceUtils.GetString("edit", 26);
            discIdLabel.Text = ResourceUtils.GetString("edit", 27);

            this.Text = movieId > 0 ? string.Format(ResourceUtils.GetString("edit", 25), movieTitle) : ResourceUtils.GetString("edit", 24);
        }
    }
}
